// 邮件操作模块（移动、删除、标记等统一操作）
const EmailOperationsManager = {
    // 初始化操作模块
    init: function() {
        // 绑定批量操作按钮
        $('#permanent-delete-selected-emails').on('click', () => this.permanentDeleteSelectedEmails());
        $('#move-selected-emails').on('click', () => this.moveSelectedEmails());
    },

    // 删除单封邮件（移动到垃圾箱）
    deleteEmail: async function(accountId, emailId) {
        // 如果是草稿箱，则调用彻底删除
        if (EmailModule.cache.currentFolder === 'Drafts') {
            return this.permanentDeleteEmail(accountId, emailId);
        }
        
        const loadingIndex = layui.layer.load(1, { shade: [0.3, '#FFF'] });
        try {
            await Api.apiRequest(`/email-accounts/${accountId}/emails`, {
                method: 'DELETE',
                body: JSON.stringify({ email_ids: [emailId] })
            });
            layui.layer.msg('删除成功');
            
            // 清空详情视图
            $('#email-detail-container').html('<div class="placeholder">请选择邮件以查看详情</div>');
            
            // 刷新邮件列表
            EmailListManager.reloadEmailList();
        } catch (error) {
            console.error('删除邮件失败:', error);
            layui.layer.msg('删除失败');
        } finally {
            layui.layer.close(loadingIndex);
        }
    },

    // 彻底删除单封邮件
    permanentDeleteEmail: async function(accountId, emailId) {
        layui.layer.confirm('确定要彻底删除这封邮件吗？此操作不可恢复。', {icon: 3, title:'提示'}, async (index) => {
            layui.layer.close(index);
            const loadingIndex = layui.layer.load(1, { shade: [0.3, '#FFF'] });
            try {
                const url = EmailModule.cache.currentFolder === 'Drafts'
                    ? `/email-accounts/${accountId}/drafts/${emailId}`
                    : `/email-accounts/${accountId}/emails/${emailId}`;
                    
                await Api.apiRequest(url, {
                    method: 'DELETE'
                });
                
                layui.layer.msg('彻底删除成功');
                
                // 如果当前查看的是被删除的邮件，清空详情视图
                if (EmailModule.cache.currentEmail && EmailModule.cache.currentEmail.id === emailId) {
                    $('#email-detail-container').html('<div class="placeholder">请选择邮件以查看详情</div>');
                }
                
                // 刷新邮件列表
                EmailListManager.reloadEmailList();
            } catch (error) {
                console.error('彻底删除邮件失败:', error);
                layui.layer.msg('彻底删除失败');
            } finally {
                layui.layer.close(loadingIndex);
            }
        });
    },

    // 标记单封邮件为已读
    markAsRead: async function(accountId, emailId) {
        const loadingIndex = layui.layer.load(1, { shade: [0.3, '#FFF'] });
        try {
            await Api.apiRequest(`/email-accounts/${accountId}/emails/mark-as-read`, {
                method: 'POST',
                body: JSON.stringify({ email_ids: [emailId] })
            });
            layui.layer.msg('标记成功');
            
            // 更新UI
            $(`.email-item[data-email-id='${emailId}']`).removeClass('unread');
        } catch (error) {
            console.error('标记已读失败:', error);
            layui.layer.msg('标记失败');
        } finally {
            layui.layer.close(loadingIndex);
        }
    },

    // 标记单封邮件为未读
    markAsUnread: async function(accountId, emailId) {
        const loadingIndex = layui.layer.load(1, { shade: [0.3, '#FFF'] });
        try {
            await Api.apiRequest(`/email-accounts/${accountId}/emails/${emailId}/read?is_read=false`, {
                method: 'PUT'
            });
            layui.layer.msg('标记成功');
            
            // 更新UI
            $(`.email-item[data-email-id='${emailId}']`).addClass('unread');
        } catch (error) {
            console.error('标记未读失败:', error);
            layui.layer.msg('标记失败');
        } finally {
            layui.layer.close(loadingIndex);
        }
    },

    // 批量删除选中的邮件（移动到垃圾箱）
    deleteSelectedEmails: async function() {
        const selectedIds = EmailListManager.getSelectedEmailIds();
        if (selectedIds.length === 0) {
            layui.layer.msg('请先选择邮件');
            return;
        }

        const loadingIndex = layui.layer.load(1, { shade: [0.3, '#FFF'] });
        try {
            await Api.apiRequest(`/email-accounts/${EmailModule.cache.currentAccount}/emails`, {
                method: 'DELETE',
                body: JSON.stringify({ email_ids: selectedIds })
            });
            layui.layer.msg('删除成功');
            
            // 如果当前查看的邮件被删除，清空详情视图
            if (selectedIds.includes(EmailModule.cache.currentEmail?.id)) {
                $('#email-detail-container').html('<div class="placeholder">请选择邮件以查看详情</div>');
            }
            
            // 退出多选模式
            EmailListManager.exitMultiSelectMode();
            
            // 刷新邮件列表
            EmailListManager.reloadEmailList();
        } catch (error) {
            console.error('删除邮件失败:', error);
            layui.layer.msg('删除失败');
        } finally {
            layui.layer.close(loadingIndex);
        }
    },

    // 批量彻底删除选中的邮件
    permanentDeleteSelectedEmails: async function() {
        const selectedIds = EmailListManager.getSelectedEmailIds();
        if (selectedIds.length === 0) {
            layui.layer.msg('请先选择要彻底删除的邮件');
            return;
        }

        layui.layer.confirm(`确定要彻底删除选中的 ${selectedIds.length} 封邮件吗？此操作不可恢复。`, {icon: 3, title:'提示'}, async (index) => {
            layui.layer.close(index);
            const loadingIndex = layui.layer.load(1, { shade: [0.3, '#FFF'] });
            try {
                const url = EmailModule.cache.currentFolder === 'Drafts'
                    ? `/email-accounts/${EmailModule.cache.currentAccount}/drafts/permanent-delete`
                    : `/email-accounts/${EmailModule.cache.currentAccount}/emails/permanent-delete`;
                await Api.apiRequest(url, {
                    method: 'POST',
                    body: JSON.stringify({ email_ids: selectedIds })
                });
                layui.layer.msg('批量彻底删除成功');
                if (selectedIds.includes(EmailModule.cache.currentEmail?.id)) {
                    $('#email-detail-container').html('<div class="placeholder">请选择邮件以查看详情</div>');
                }
                EmailListManager.exitMultiSelectMode();
                EmailListManager.reloadEmailList();
            } catch (error) {
                console.error('批量彻底删除邮件失败:', error);
                layui.layer.msg('批量彻底删除失败');
            } finally {
                layui.layer.close(loadingIndex);
            }
        });
    },

    // 移动邮件
    moveEmail: async function(accountId, emailId, currentFolder) {
        // 从DOM缓存中获取邮件文件夹信息
        const emailItem = $(`.email-item[data-email-id="${emailId}"]`);
        let emailFolders = [];
        
        if (emailItem.length) {
            const cachedFolders = emailItem.data('email-folders');
            if (cachedFolders) {
                try {
                    emailFolders = JSON.parse(cachedFolders);
                } catch (e) {
                    console.error('解析缓存的文件夹信息失败:', e);
                }
            }
        }
        
        const isVirtualFolder = ['UNREAD', 'STARRED', 'FLAGGED'].includes(currentFolder);
        const realFolders = emailFolders.filter(f => !['UNREAD', 'STARRED', 'FLAGGED'].includes(f));
        
        console.log('邮件移动 - 当前文件夹:', currentFolder, '是否虚拟:', isVirtualFolder, '缓存的文件夹:', emailFolders, '真实文件夹:', realFolders);
        
        // 如果在虚拟文件夹中且邮件存在于多个真实文件夹，需要先选择源文件夹
        if (isVirtualFolder && realFolders.length > 1) {
            let sourceFolderHtml = '<div style="padding: 20px;"><p style="margin-bottom: 15px;">该邮件存在于多个文件夹中，请选择要从哪个文件夹移动：</p><div class="layui-form">';
            realFolders.forEach(folderName => {
                sourceFolderHtml += `
                    <div style="margin: 10px 0;">
                        <button type="button" class="layui-btn layui-btn-primary" style="width: 100%;" data-source-folder="${escapeHtml(folderName)}">
                            ${escapeHtml(folderName)}
                        </button>
                    </div>
                `;
            });
            sourceFolderHtml += '</div></div>';
            
            const sourceFolderIndex = layer.open({
                type: 1,
                title: '选择源文件夹',
                area: ['400px', 'auto'],
                content: sourceFolderHtml,
                btn: ['取消'],
                success: function(layero, index) {
                    layero.find('button[data-source-folder]').on('click', function() {
                        const selectedSourceFolder = $(this).data('source-folder');
                        layer.close(index);
                        EmailOperationsManager.continueMoveEmail(accountId, emailId, selectedSourceFolder);
                    });
                }
            });
            return;
        }
        
        // 确定实际的源文件夹
        let actualSourceFolder;
        if (isVirtualFolder) {
            actualSourceFolder = realFolders.length > 0 ? realFolders[0] : currentFolder;
        } else {
            actualSourceFolder = currentFolder;
        }
        
        console.log('使用源文件夹:', actualSourceFolder);
        
        this.continueMoveEmail(accountId, emailId, actualSourceFolder);
    },
    
    // 继续移动邮件流程
    continueMoveEmail: async function(accountId, emailId, sourceFolder) {
        const loadingIndex = layui.layer.load(1, { shade: [0.3, '#FFF'] });
        try {
            const folders = await Api.apiRequest(`/email-accounts/${accountId}/folders?force_sync=false`);
            if (!folders || folders.length === 0) {
                layui.layer.msg('无法获取文件夹列表');
                return;
            }
            
            const treeData = EmailListManager.formatTreeData(folders);

            layer.open({
                type: 1,
                title: `从 ${sourceFolder} 移动到`,
                area: ['400px', 'auto'],
                content: '<div id="folder-tree" class="folder-tree-panel"></div>',
                maxmin: true,
                shadeClose: true,
                success: function(layero, index) {
                    layui.tree.render({
                        elem: '#folder-tree',
                        data: treeData,
                        id: 'folderTree',
                        accordion: true,
                        onlyIconControl: true,
                        click: async function(obj) {
                            const targetFolder = obj.data.id;
                            layer.close(index);
                            const moveLoadingIndex = layui.layer.load(1, { shade: [0.3, '#FFF'] });
                            try {
                                await Api.apiRequest(`/email-accounts/${accountId}/emails/${emailId}/move?source_folder=${encodeURIComponent(sourceFolder)}`, {
                                    method: 'POST',
                                    body: JSON.stringify({
                                        target_folder: targetFolder
                                    })
                                });
                                layui.layer.msg('移动成功');
                                if (EmailModule.cache.currentEmail && EmailModule.cache.currentEmail.id === emailId) {
                                    $('#email-detail-container').html('<div class="placeholder">请选择邮件以查看详情</div>');
                                }
                                EmailListManager.reloadEmailList();
                            } catch (error) {
                                console.error('移动邮件失败:', error);
                                layui.layer.msg('移动邮件失败');
                            } finally {
                                layui.layer.close(moveLoadingIndex);
                            }
                        }
                    });
                }
            });
        } catch (error) {
            console.error('获取文件夹失败:', error);
            layui.layer.msg('获取文件夹列表失败');
        } finally {
            layui.layer.close(loadingIndex);
        }
    },

    // 批量移动邮件
    moveSelectedEmails: async function() {
        const selectedIds = EmailListManager.getSelectedEmailIds();
        if (selectedIds.length === 0) {
            layui.layer.msg('请先选择要移动的邮件');
            return;
        }

        const currentFolder = EmailModule.cache.currentFolder;
        const isVirtualFolder = ['UNREAD', 'STARRED', 'FLAGGED'].includes(currentFolder);
        
        if (isVirtualFolder) {
            const emailsInfo = [];
            let hasMultiFolderEmail = false;
            
            for (const emailId of selectedIds) {
                const emailItem = $(`.email-item[data-email-id="${emailId}"]`);
                if (emailItem.length) {
                    const cachedFolders = emailItem.attr('data-email-folders');
                    let folders = [];
                    
                    if (cachedFolders) {
                        try {
                            folders = JSON.parse(cachedFolders);
                        } catch (e) {
                            console.error('解析缓存的文件夹信息失败:', e);
                        }
                    }
                    
                    const realFolders = folders.filter(f => !['UNREAD', 'STARRED', 'FLAGGED'].includes(f));
                    
                    console.log(`邮件 ${emailId} - 所有文件夹:`, folders, '真实文件夹:', realFolders);
                    
                    if (realFolders.length > 1) {
                        hasMultiFolderEmail = true;
                        break;
                    }
                    
                    emailsInfo.push({
                        id: emailId,
                        folders: realFolders
                    });
                }
            }
            
            if (hasMultiFolderEmail) {
                layui.layer.msg('所选邮件存在于多个文件夹中，批量移动操作不可用，请单独移动', { icon: 7, time: 3000 });
                return;
            }
            
            this.batchMoveWithSourceFolders(selectedIds, emailsInfo);
            return;
        }

        // 在真实文件夹中，直接批量移动
        const loadingIndex = layui.layer.load(1, { shade: [0.3, '#FFF'] });
        try {
            const folders = await Api.apiRequest(`/email-accounts/${EmailModule.cache.currentAccount}/folders?force_sync=false`);
            if (!folders || folders.length === 0) {
                layui.layer.msg('无法获取文件夹列表');
                return;
            }
            
            const treeData = EmailListManager.formatTreeData(folders);

            layer.open({
                type: 1,
                title: `从 ${currentFolder} 批量移动 ${selectedIds.length} 封邮件`,
                area: ['400px', 'auto'],
                content: '<div id="folder-tree" class="folder-tree-panel"></div>',
                maxmin: true,
                shadeClose: true,
                success: function(layero, index) {
                    layui.tree.render({
                        elem: '#folder-tree',
                        data: treeData,
                        id: 'folderTree',
                        accordion: true,
                        onlyIconControl: true,
                        click: async function(obj) {
                            const targetFolder = obj.data.id;
                            layer.close(index);

                            const moveLoadingIndex = layui.layer.load(1, { shade: 0.3 });
                            let successCount = 0;
                            let failCount = 0;

                            for (const emailId of selectedIds) {
                                try {
                                    await Api.apiRequest(`/email-accounts/${EmailModule.cache.currentAccount}/emails/${emailId}/move?source_folder=${encodeURIComponent(currentFolder)}`, {
                                        method: 'POST',
                                        body: JSON.stringify({
                                            target_folder: targetFolder
                                        })
                                    });
                                    successCount++;
                                } catch (error) {
                                    failCount++;
                                    console.error(`邮件 ${emailId} 移动失败:`, error);
                                }
                            }

                            layui.layer.close(moveLoadingIndex);

                            if (failCount === 0) {
                                layui.layer.msg(`成功移动 ${successCount} 封邮件`);
                            } else {
                                layui.layer.msg(`成功移动 ${successCount} 封，失败 ${failCount} 封`);
                            }

                            if (selectedIds.includes(EmailModule.cache.currentEmail?.id)) {
                                $('#email-detail-container').html('<div class="placeholder">请选择邮件以查看详情</div>');
                            }

                            EmailListManager.exitMultiSelectMode();
                            EmailListManager.reloadEmailList();
                        }
                    });
                }
            });
        } catch (error) {
            console.error('获取文件夹失败:', error);
            layui.layer.msg('获取文件夹列表失败');
        } finally {
            layui.layer.close(loadingIndex);
        }
    },
    
    // 批量移动邮件（带源文件夹信息）
    batchMoveWithSourceFolders: async function(selectedIds, emailsInfo) {
        const loadingIndex = layui.layer.load(1, { shade: [0.3, '#FFF'] });
        try {
            const folders = await Api.apiRequest(`/email-accounts/${EmailModule.cache.currentAccount}/folders?force_sync=false`);
            if (!folders || folders.length === 0) {
                layui.layer.msg('无法获取文件夹列表');
                return;
            }
            
            const treeData = EmailListManager.formatTreeData(folders);

            layer.open({
                type: 1,
                title: `批量移动 ${selectedIds.length} 封邮件`,
                area: ['400px', 'auto'],
                content: '<div id="folder-tree" class="folder-tree-panel"></div>',
                maxmin: true,
                shadeClose: true,
                success: function(layero, index) {
                    layui.tree.render({
                        elem: '#folder-tree',
                        data: treeData,
                        id: 'folderTree',
                        accordion: true,
                        onlyIconControl: true,
                        click: async function(obj) {
                            const targetFolder = obj.data.id;
                            layer.close(index);

                            const moveLoadingIndex = layui.layer.load(1, { shade: 0.3 });
                            let successCount = 0;
                            let failCount = 0;

                            for (let i = 0; i < selectedIds.length; i++) {
                                const emailId = selectedIds[i];
                                const emailInfo = emailsInfo[i];
                                
                                const realFolders = (emailInfo.folders || []).filter(f => !['UNREAD', 'STARRED', 'FLAGGED'].includes(f));
                                const sourceFolder = realFolders[0];
                                
                                try {
                                    await Api.apiRequest(`/email-accounts/${EmailModule.cache.currentAccount}/emails/${emailId}/move?source_folder=${encodeURIComponent(sourceFolder)}`, {
                                        method: 'POST',
                                        body: JSON.stringify({
                                            target_folder: targetFolder
                                        })
                                    });
                                    successCount++;
                                } catch (error) {
                                    failCount++;
                                    console.error(`邮件 ${emailId} 从 ${sourceFolder} 移动失败:`, error);
                                }
                            }

                            layui.layer.close(moveLoadingIndex);

                            if (failCount === 0) {
                                layui.layer.msg(`成功移动 ${successCount} 封邮件`);
                            } else {
                                layui.layer.msg(`成功移动 ${successCount} 封，失败 ${failCount} 封`);
                            }

                            if (selectedIds.includes(EmailModule.cache.currentEmail?.id)) {
                                $('#email-detail-container').html('<div class="placeholder">请选择邮件以查看详情</div>');
                            }

                            EmailListManager.exitMultiSelectMode();
                            EmailListManager.reloadEmailList();
                        }
                    });
                }
            });
        } catch (error) {
            console.error('获取文件夹失败:', error);
            layui.layer.msg('获取文件夹列表失败');
        } finally {
            layui.layer.close(loadingIndex);
        }
    }
};